#include <signal.h>
#include <unistd.h>
#include <rapidjson/document.h>

  



#include <iostream> 

#include "websocket_endpoint.h"
#include "trace_worker.h"
#include "JsonHelper.h"

void whenSigInt(int)
{
    trace_stop();
	printf("trace_stoptrace_stoptrace_stoptrace_stop\n");
	exit(0);
}


int main(int argc, char* argv[])
{
    signal(SIGSEGV, whenSigInt);
    signal(SIGINT, whenSigInt);
    signal(SIGABRT, whenSigInt);
    trace_start("./1111.cpp", false);

    if (argc != 3)
    {
        printf("ws-client openId cmd.json\n");
        return -1;
    }

    CWsClient wsClient;
    const std::string uri = std::string("ws://localhost:8000/") + argv[1];
    if (wsClient.Connect(uri) == false)
    {
        printf("connect %s failed\n", uri.c_str());
        return -1;
    }
    sleep(1);

    std::ifstream ifs(argv[2]);
    rapidjson::IStreamWrapper isw(ifs);
    rapidjson::Document document;

    if (document.ParseStream(isw).HasParseError())
    {
        printf("GetParseError %d\n", document.GetParseError());
        return -1;
    }

    rapidjson::Value &cmdArraryValue = document;
    for (int time=0; time<10000; ++time)
    {
        for (unsigned int cmdArraryIndex=0; cmdArraryIndex<cmdArraryValue.Size(); ++cmdArraryIndex)
        {
            const rapidjson::Value &cmdValue = cmdArraryValue[cmdArraryIndex];
            const int &interval = cmdValue["interval"].GetInt();
            const std::string &method = cmdValue["method"].GetString();

            rapidjson::StringBuffer buffer;
            wsClient.Send(method + ":" + CJsonHelper::toString(cmdValue["content"], buffer));
            usleep(1000 * interval);
        }
    }

    trace_stop();
    return 0;
}



